//
//  NetHandler.m
//  Day18_UI_作业1_崔嵬
//
//  Created by Damon on 14/12/7.
//  Copyright (c) 2014年 崔嵬. All rights reserved.
//

#import "NetHandler.h"

@implementation NetHandler


+ (void)getDataWithURL:(NSString *)str completion:(void (^)(NSData *))block
{
    NSString *Urlstr = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:Urlstr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100];
    
    request.HTTPMethod = @"get";
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
       
        NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        NSString *cacheDirectory = [docPath stringByAppendingPathComponent:@"myCaches"];
        

        
        if (![fileManager isExecutableFileAtPath:@"myCaches"]) {
        [fileManager createDirectoryAtPath:cacheDirectory withIntermediateDirectories:YES attributes:nil error:nil];
        }
        
        
        
        NSString *strPath = [NSString stringWithFormat:@"%ld.aa", [str hash]];
        
        NSString *path = [cacheDirectory stringByAppendingPathComponent:strPath];

        
        if (data != nil) {
           // BOOL result = [NSKeyedArchiver archiveRootObject:data toFile:path];
            //NSLog(@"%d", result);
            block(data);
        } else {
            
            NSData *pickData = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
            if (pickData != nil) {
                block(pickData);
            }
            
        }
        
    }];
    
    
}

@end
